import React, {PureComponent} from 'react';
import {
  View,
  StyleSheet,
  Text,
  TextInput,
  Image,
  TouchableOpacity,
  TouchableWithoutFeedback,
  Keyboard,
  PermissionsAndroid,
  Platform,
  Button,
} from 'react-native';
import I18n from 'react-native-i18n';
import {connect} from 'react-redux';
import BaseComponent from '../base/BaseComponent';
import {
  ImageButton,
  LinearBoardButton,
  LinearButton,
  TextButton,
} from '../../components/Button';
import WalletUtils from '../../utils/wallet/WalletUtils';
import {LinerBoardTextInput} from '../../components/TextInput';
import {NormalHeader} from '../../components/NavigationHeader';
import {follow, getUserReward, rewardConvert, query} from '../../api/user';
import {showToast} from '../../components/Toast';
import {updateUserInfo} from '../../redux/action';
import Clipboard from '@react-native-community/clipboard';
import {BASE_API} from '../../config';
import LinearGradient from 'react-native-linear-gradient';
import {ScrollView} from 'react-native-gesture-handler';
import ModalHandler from '../../components/ModalHandler';

class MyClubScreen extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      loading: false,
      success: false,
      amount: '',
      totalReward: 0,
      convertReward: 0,
      rewards: [],
      page: 1,
      totalNum: 0,
    };
  }

  componentDidMount() {
    this.getRewards(1);
    this._queryUserInfo();
  }

  _queryUserInfo = () => {
    query({
      userToken: this.props.userInfo.token,
    }).then((resp) => {
      let user = resp.data;
      console.log('reward data', user);
      this.setState({
        totalReward: user.totalReward ? user.totalReward : 0,
        convertReward: user.convertReward ? user.convertReward : 0,
      });
    });
  };

  reloadData = () => {
    this.setState({
      loading: false,
      success: false,
      amount: '',
    });
    this.getRewards(1);
    this._queryUserInfo();
  };

  formatNum = (num) => {
    if (!num) return '0';
    return num;
  };

  calPageLength = (totalNum, size) => {
    return Math.floor(totalNum / size) + (totalNum % size == 0 ? 0 : 1);
  };

  getRewards = (page) => {
    let pageSize = 10;
    if (page < 1) {
      return;
    }
    if (page != 1 && this.calPageLength(this.state.totalNum, pageSize) < page) {
      return;
    }
    this.setState({
      page: page,
    });
    getUserReward({
      userToken: this.props.userInfo.token,
      size: pageSize,
      page: page,
    }).then((resp) => {
      console.log('getUserReward', JSON.stringify(resp));
      this.setState({
        rewards: resp.data.rows,
        totalNum: resp.data.pageInfo.total,
      });
    });
  };

  _handlerView = () => {
    return (
      <View style={{width: '100%'}}>
        <Text
          style={{
            marginTop: 0,
            lineHeight: 40,
            color: '#6902F4',
            fontSize: 18,
          }}>
          Confirm your transaction
        </Text>
        <Image
          style={{height: 1, width: '100%', marginBottom: 20}}
          source={require('../../assets/auction/line.png')}></Image>
        <View style={{width: '100%'}}>
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              width: '100%',
              marginTop: 0,
            }}>
            <Text style={{lineHeight: 30, color: '#6902F4'}}>
              Call Function
            </Text>
            <Text
              style={{
                fontWeight: 'bold',
                color: '#6902F4',
                lineHeight: 30,
              }}>
              apply for convert
            </Text>
          </View>
        </View>
        <LinerBoardTextInput
          placeholder="Amount"
          keyboardType="numeric"
          defaultValue={this.state.amount}
          onChangeText={(text) => {
            this.setState({
              amount: text,
            });
          }}
        />
        <View
          style={{
            flexDirection: 'row',
            justifyContent: 'flex-end',
            width: '100%',
            // marginTop: 10,
            marginBottom: 20,
          }}>
          <LinearBoardButton
            buttonStyle={{width: 100, height: 35, marginRight: 20}}
            text="Cancel"
            onPress={() => {
              this.setState({
                modalVisible: false,
              });
            }}
          />
          <LinearButton
            buttonStyle={{width: 100, height: 35, marginRight: 20}}
            text="Confirm"
            onPress={this.handlerConfirm}
          />
        </View>
      </View>
    );
  };

  handlerConfirm = () => {
    if (!this.state.amount) {
      return;
    }
    Keyboard.dismiss();

    this.setState(
      {
        loading: true,
      },
      async () => {
        rewardConvert({
          userToken: this.props.userInfo.token,
          amount: this.state.amount,
        })
          .then((resp) => {
            console.log('success');
            if (resp.code == 200) {
              this.setState({
                amount: '',
                modalVisible: false,
                loading: false,
              });
              this.reloadData();
            }
          })
          .catch((err) => {
            console.log(err);
            // this._showAlert(err.msg || 'network error');
            this.setState({
              loading: false,
            });
          });
      },
    );
  };

  onPressBackground = () => {
    if (this.state.loading) {
      return;
    }

    this.setState({
      modalVisible: false,
      loading: false,
    });
  };

  renderComponent = () => {
    return (
      <View style={{flex: 1, backgroundColor: '#160231'}}>
        <NormalHeader
          navigation={this.props.navigation}
          text="My Club"
          left={{
            icon: require('../../assets/common/common_back_white.png'),
            onPress: () => {
              console.log(111);
              Keyboard.dismiss();
              this.props.navigation.goBack();
            },
          }}
          right={{
            containerStyle: {
              width: 100,
            },
            text: 'Rules',
            onPress: () => {
              Keyboard.dismiss();
              this.props.navigation.navigate('ApplyClub');
            },
          }}
        />

        <ScrollView>
          <View
            style={{
              paddingHorizontal: 20,
              alignItems: 'center',
            }}>
            <View
              style={{
                flexDirection: 'row',
                paddingHorizontal: 20,
                paddingVertical: 40,
              }}>
              <View
                style={{
                  flex: 1,
                  flexDirection: 'column',
                  alignItems: 'center',
                }}>
                <Text
                  style={{
                    color: '#fff',
                    fontSize: 25,
                    fontWeight: 'bold',
                  }}>
                  {this.formatNum(
                    this.state.totalReward - this.state.convertReward,
                  )}
                </Text>
                <Text
                  style={{
                    color: '#fff',
                    fontSize: 20,
                    marginTop: 12,
                    fontWeight: 'bold',
                  }}>
                  Not Redeemed
                </Text>
              </View>

              <View
                style={{
                  flex: 1,
                  flexDirection: 'column',
                  alignItems: 'center',
                }}>
                <Text
                  style={{
                    color: '#fff',
                    fontSize: 25,
                    fontWeight: 'bold',
                  }}>
                  {this.formatNum(this.state.convertReward)}
                </Text>
                <Text
                  style={{
                    color: '#fff',
                    fontSize: 20,
                    marginTop: 12,
                    fontWeight: 'bold',
                  }}>
                  Redeemed
                </Text>
              </View>
            </View>

            <TouchableWithoutFeedback
              onPress={() => {
                this.setState({
                  modalVisible: true,
                });
              }}>
              <Image
                style={{
                  width: 375,
                  height: 172,
                  borderRadius: 10,
                }}
                source={require('../../assets/user/club_banner.png')}></Image>
            </TouchableWithoutFeedback>

            <View
              style={{
                margin: 40,
                backgroundColor: '#443559',
                padding: 16,
                width: '100%',
                borderRadius: 16,
              }}>
              <Text
                style={{
                  color: '#fff',
                  fontWeight: 'bold',
                  fontSize: 18,
                  marginBottom: 20,
                }}>
                Award Record
              </Text>
              {this.state.rewards.map((item, index) => {
                return (
                  <View key={index}>
                    <View
                      style={{
                        flexDirection: 'row',
                      }}>
                      <Text
                        style={{
                          color: '#D8D8D8',
                          fontSize: 14,
                          width: 100,
                        }}>
                        {item.remark}
                      </Text>
                      <Text
                        style={{
                          color: '#D8D8D8',
                          fontSize: 14,
                          marginLeft: 4,
                          flex: 1,
                        }}>
                        {item.income == 1 ? '+' : '-'}
                        {item.amount}
                      </Text>
                      <Text
                        style={{
                          color: '#D8D8D8',
                          fontSize: 14,
                        }}>
                        {item.createTime}
                      </Text>
                    </View>
                    <Image
                      style={{
                        width: '100%',
                        marginTop: 4,
                      }}
                      source={require('../../assets/user/divider.png')}></Image>
                  </View>
                );
              })}
              <View
                style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'center',
                  marginTop: 10,
                }}>
                <ImageButton
                  btnStyle={{
                    width: 30,
                    height: 30,
                  }}
                  imageStyle={{
                    width: 15,
                    height: 15,
                  }}
                  source={require('../../assets/common/common_back_white.png')}
                  onPress={() => {
                    this.getRewards(this.state.page - 1);
                  }}></ImageButton>
                <Text
                  style={{
                    marginHorizontal: 10,
                    color: '#fff',
                  }}>
                  {this.state.page}
                </Text>
                <ImageButton
                  btnStyle={{
                    width: 30,
                    height: 30,
                  }}
                  imageStyle={{
                    width: 15,
                    height: 15,
                  }}
                  source={require('../../assets/common/backwhite_icon.png')}
                  onPress={() => {
                    this.getRewards(this.state.page + 1);
                  }}></ImageButton>
              </View>
            </View>
          </View>
          <View
            style={{
              width: '100%',
              height: this.props.widgetLayout.show
                ? this.props.widgetLayout.height
                : 0,
              marginTop: 10,
            }}></View>
        </ScrollView>
        <ModalHandler
          visible={this.state.modalVisible}
          loading={this.state.loading}
          success={this.state.success}
          handlerView={this._handlerView}
          onPressBackground={this.onPressBackground}
        />
      </View>
    );
  };
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
  widgetLayout: state.Layout.widgetLayout,
});

const mapDispatchToProps = (dispatch) => ({
  userLogout: (item) => dispatch(userLogout()),
});

export default connect(mapStateToProps, mapDispatchToProps)(MyClubScreen);
